package org.example.nt.ali;

import com.aliyun.gmsse.GMProvider;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslHandler;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;

public class NettyClientInitializer extends ChannelInitializer<SocketChannel> {
    private static final Provider BC = new BouncyCastleProvider();
    static {
        Security.addProvider(BC);
    }
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        socketChannel.pipeline().addLast("tls", createSslHandler(getClientSSLContext()));
        socketChannel.pipeline().addLast("decoder", new StringDecoder());
        socketChannel.pipeline().addLast("encoder", new StringEncoder());
        socketChannel.pipeline().addLast(new NettyClientHandler());
    }

    private ChannelHandler createSslHandler(SSLContext sslContext)
    {
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(true);
        sslEngine.setNeedClientAuth(false);
        return new SslHandler(sslEngine);
    }

    private SSLContext getClientSSLContext() throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, KeyManagementException {
        KeyStore trustKeyStore = KeyStore.getInstance("BouncyCastle", BC);

//        KeyStore trustKeyStore = KeyStore.getInstance("JKS");
//        FileInputStream fileInputStream = new FileInputStream("D:\\ws\\java\\springboot-demo\\netty-demo\\sm\\sm-client.ks");
//        char[] pass = "000000".toCharArray();
//        trustKeyStore.load(fileInputStream, null);
//
//        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//        trustManagerFactory.init(trustKeyStore);
//
//        SSLContext clientContext = SSLContext.getInstance("TLS");
//        clientContext.init(null, trustManagerFactory.getTrustManagers(), null);

        GMProvider provider = new GMProvider();
        SSLContext sc = SSLContext.getInstance("TLS", provider);
        sc.init(null, new TrustManager[]{}, new SecureRandom());
        return sc;
    }
}
